<template>
  <div class="user-content">
    <client-only>
      <div class="person_body">
        <el-tabs tab-position="left" v-model="leftActionName" @tab-click="leftHandleClick">
          <!--个人信息-->
          <el-tab-pane label="个人信息" name="info">
            <el-tabs tab-position="top" type="card">
              <el-tab-pane label="基础信息">
                <el-form label-width="80px">
                  <el-form-item label="头像">
                    <el-upload
                      :show-file-list="false"
                      :headers="headerObj"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload"
                      :action="baseUrl+'/educenter/ucenter/fileoss?host=ucenter'"
                      style="width: 100%">
                      <img :src="tempUser.avatar" alt="头像" style="width: 120px;border-radius: 50%;">
                    </el-upload>
                    <span class="fr color9">（点击图片修改，图片大小不超过2M）</span>
                  </el-form-item>
                  <el-form-item label="用户名">{{tempUser.email}}<span class="fr color9">不可修改</span></el-form-item>

                  <el-form-item label="昵称">
                    <el-input v-if="isResetNickName" v-model="tempNickName" placeholder="请输入内容"
                              style="width: 50%"></el-input>
                    <span v-else>{{tempUser.nickname}}</span>
                    <a :class="['fr', {'color9':!isResetNickName}]" @click="resetNickName()">{{isResetNickName?'保存':'编辑'}}</a>
                  </el-form-item>

                  <el-form-item label="年龄">
                    <el-input-number v-if="isResetAge" v-model="tempUser.age" controls-position="right" :min="1"
                                     :max="100"></el-input-number>
                    <span v-else>{{tempUser.age}}</span>
                    <a :class="['fr', {'color9':!isResetAge}]" @click="resetAge()">{{isResetAge?'保存':'编辑'}}</a>
                  </el-form-item>

                  <el-form-item label="性别">
                    <template v-if="isResetSex" style="width: 50%">
                      <el-radio v-model="tempUser.sex" :label=1>女</el-radio>
                      <el-radio v-model="tempUser.sex" :label=2>男</el-radio>
                    </template>
                    <span v-else>{{$enum.getDescByValue("SEX",tempUser.sex||0)}}</span>
                    <a :class="['fr', {'color9':!isResetSex}]" @click="resetSex()">{{isResetSex?'保存':'编辑'}}</a>

                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
          <!--修改密码-->
          <el-tab-pane label="修改密码" name="pwd">
            <el-tabs tab-position="top" type="card">
              <el-tab-pane label="修改密码">
                <el-form label-width="80px" ref="changUserForm" :model="userParams" :rules="registerRules">
                  <el-form-item label="邮箱" prop="email">
                    <el-input disabled :value="tempUser.email"></el-input>
                  </el-form-item>
                  <el-form-item label="验证码" prop="code">
                    <div style="width: 100%;display: block;float: left;position: relative">
                      <el-input type="text" v-model="userParams.code">
                        <template slot="append">
                          <div class="btn send-code">
                            <a v-if="sending" href="javascript:" disabled="true" type="button" @click="getCodeFun()"
                               :value="codeTest">{{codeTest}}</a>
                            <span v-else>{{codeTest}}</span>
                          </div>
                        </template>
                      </el-input>

                    </div>

                  </el-form-item>

                  <el-form-item label="重置密码" prop="password">
                    <el-input v-model="userParams.password" type="password" show-password></el-input>
                  </el-form-item>
                  <el-form-item label="确认密码" prop="pwd2">
                    <el-input v-model="userParams.pwd2" type="password" show-password></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="editPwd()">提交</el-button>
                    <el-button>重置</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
          <!--我的订单-->
          <el-tab-pane label="我的订单" name="order">
            <el-tabs tab-position="top" v-model="orderActionName" @tab-click="orderHandleClick">
              <el-tab-pane name="all" label="所有订单"></el-tab-pane>
              <el-tab-pane name="0" label="未支付订单"></el-tab-pane>
              <el-tab-pane name="1" label="已支付订单"></el-tab-pane>
            </el-tabs>
            <!--暂无记录-->
            <section v-if="!orderList[0]" class="no-data-wrap">
              <em class="icon30 no-data-ico">&nbsp;</em>
              <span class="c-666 fsize14 ml10 vam">没有相关数据</span>
            </section>
            <!-- 订单记录-->
            <div v-else class="project-content" v-for="(item,index) in orderList"
                 :key="index">
              <div class="project-item" @click="toCourse(item.targetType,item.targetId)">
                <div class="item-thumb">
                  <img :src="item.courseCover" alt="">
                </div>
                <div class="item-info">
                  <div class="item-top">
                    <div class="item-name"> {{item.courseTitle}}</div>
                    <div class="order-num"> 订单编号：{{item.orderNo}}</div>
                    <div class="item-time"> {{item.gmtCreate | formatTime}}</div>
                  </div>
                  <div class="item-bottom">
                    <span class="course-tag" :class="'tag'+item.targetType">
                      {{$enum.getDescByValue('COURSE_TYPE', item.targetType) }}
                    </span>
                    <div class="item-price">实付款：￥{{item.totalFee}}</div>
                    <div :class="['item-status',item.status===0?'act':'suc']">
                      {{$enum.getDescByValue('PAY_STATUS',item.status) }}
                    </div>
                  </div>
                </div>
              </div>
            </div>

          </el-tab-pane>
          <!--收藏记录-->
          <el-tab-pane label="收藏记录" name="collect">
            <el-tabs tab-position="top" v-model="collectActionName" @tab-click="collectHandleClick">
              <el-tab-pane name="1" label="录播课"></el-tab-pane>
              <el-tab-pane name="3" label="图文"></el-tab-pane>
              <el-tab-pane name="4" label="学习路径"></el-tab-pane>
            </el-tabs>
            <!--暂无记录-->
            <section v-if="!collectList" class="no-data-wrap">
              <em class="icon30 no-data-ico">&nbsp;</em>
              <span class="c-666 fsize14 ml10 vam">没有相关数据</span>
            </section>
            <!--录播课收藏记录-->
            <div v-else class="project-content" v-for="(item,index) in collectList"
                 :key="index">
              <div class="project-item" @click="toCourse(targetType,item.id)">
                <div class="item-thumb">
                  <img :src="item.cover ||item.coverImage" alt="">
                </div>
                <div class="item-info">
                  <div class="item-top">
                    <div class="item-name"> {{item.title}}</div>
                  </div>
                  <div class="item-bottom">
                    <div class="item-free">免费</div>
                  </div>
                </div>
              </div>
            </div>
            <!--暂无记录-->
          </el-tab-pane>
        </el-tabs>
      </div>


    </client-only>
  </div>
</template>
<script>
  import {mapGetters} from 'vuex'
  import collectApi from '@/api/collectApi'
  import orderApi from '@/api/order'
  import loginApi from '@/api/login'
  import userApi from '@/api/userApi'
  import commonUtil from "@/utils/commonUtil";
  import appConfig from '@/utils/app-config';
  import cookie from "js-cookie";

  export default {

    data() {
      let validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.userParams.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      return {
        leftActionName: 'info',
        collectActionName: '1',
        orderActionName: 'all',
        targetType: 1,
        collectList: [],

        orderList: [],
        orderStatus: '',
        baseUrl: appConfig.idcUrlConfig.baseURL,
        isResetNickName: false,
        isResetAge: false,
        isResetSex: false,
        headerObj: {
          "front-token": cookie.get('we_token')
        },
        tempUser: {},

        userParams: {
          email:'',
          code: '',
          password: '',
          pwd2: '',
        },
        codeTest: '获取验证码',
        second: 60,        //倒计时间
        sending: true,      //能否发送验证码
        registerRules: {
          // email: [{required: true, message: '请输入邮箱', trigger: 'blur'}],
          code: [{required: true, message: '请输入验证码', trigger: 'blur'}]
          , password: [{required: true, message: '请输入密码', trigger: 'blur'}]
          , pwd2: [{required: true, message: '请确认密码', trigger: 'blur', validator: validatePass2}]
        },

      }
    }, computed: {
      ...mapGetters([
        'loginInfo',
      ])
    },
    mounted() {
      this.tempUser = Object.assign({}, this.loginInfo)
      /* created:在模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图。
         mounted:在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作。*/
    }, filters: {
      formatTime(value) {
        return commonUtil.changeTime(value)
      }
    },
    created() {
      if (!this.loginInfo.id) {
        this.$router.push("/")
      }
    }
    , methods: {
      toCourse(type, id) {
        let toInfo = this.$router.resolve(
          {path: `/${this.$enum.getObjByValue('COURSE_TYPE', Number.parseInt(type)).path}/` + id})
        window.open(toInfo.href, '_blank')
      },
      editPwd() {
        this.$refs['changUserForm'].validate((valid) => {
          if (valid) {
            this.userParams.email=this.tempUser.email
            userApi.changePassword(this.userParams).then(res => {
              this.$message.success("修改成功")
              this.$store.dispatch('logOut')
              this.$router.push("login")

            })
          }
        })

      },
      getCodeFun() {
        if (!this.sending)
          return;
        userApi.sendChangEmailCode(this.tempUser.email).then(res => {
          this.sending = false;
          this.timeDown();
        });
      },
      timeDown() {
        let result = setInterval(() => {
          --this.second;
          this.codeTest = this.second
          if (this.second < 1) {
            clearInterval(result);
            this.sending = true;
            //this.disabled = false;
            this.second = 60;
            this.codeTest = "获取验证码"
          }
        }, 1000);

      },
      //左侧菜单栏点击事件
      leftHandleClick(tab, event) {
        // console.log(tab, event);
        //console.log(tab.name);
        if (tab.name === "collect") {
          this.targetType = 1
          this.getCollect()

        } else if (tab.name === "order") {
          orderApi.getList(this.orderStatus).then(res => {
            this.orderList = res
          })
        }
      },
      //收藏记录tab点击事件
      //todo 请求优化
      collectHandleClick(tab, event) {
        this.targetType = tab.name;
        this.getCollect()
      },
      orderHandleClick(tab, event) {
        this.orderStatus = tab.name === 'all' ? '' : tab.name
        this.getOrderList()

      },
      getCollect() {
        collectApi.getList(this.targetType).then(res => {
          this.collectList = res
          console.log(this.orderList)
        })
      },
      getOrderList() {
        orderApi.getList(this.orderStatus).then(res => {
          this.orderList = res
          console.log(this.orderList)
          // console.log(this.orderList.length)

        })
      },
      //头像上传成功之后
      handleAvatarSuccess(res, file) {
        this.tempUser.avatar = res.info
        this.resetUser()
      },
      //上传之前调用的方法 约定文件类型
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        const typeArr = ['image/jpeg', 'image/png', 'image/jpg']
        console.log(file.type)
        const isImage = typeArr.find(x => x === file.type);
        if (!isImage) {
          this.$message.error('仅支持jpeg/png/jpg格式类型的头像')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return isImage && isLt2M
      },
      resetUser() {
        loginApi.resetUser(this.tempUser).then(res => {
          this.$store.dispatch('reloadUser',this.tempUser)
        })
      }, resetNickName() {
        this.isResetNickName = !this.isResetNickName
        if (!this.isResetNickName) {
          this.resetUser()

        }
      }, resetAge() {
        this.isResetAge = !this.isResetAge
        if (!this.isResetAge) {
          this.resetUser()
        }
      }, resetSex() {
        this.isResetSex = !this.isResetSex
        if (!this.isResetSex) {
          this.resetUser()
        }
      }
    }
  }
</script>
<style scoped>
  [v-cloak] {
    display: none;
  }

  /*父元素*/
  .user-content {
    /*子元素设置margin-top后，父元素跟随下移的问题
    当一个元素包含在另一个元素中时，假设没有内边距padding或边框border把外边距分隔开，它们的上和/或下外边距也会发生合并
    为父元素添加overflow：hidden；样式即可*/
    overflow: hidden;
    background: #fafafa;
    min-height: 500px;
  }

  /*子元素*/
  .person_body {
    width: 1200px;
    margin: 30px auto;
    min-height: 500px;
    background: #fff;
    padding: 30px;
    border-radius: 8px;
  }

  /*左侧tab*/
  /deep/ .is-left .el-tabs__nav-scroll {
    float: left;
    width: 168px;
    /*border-left: 1px solid #ccc;*/
  }

  /deep/ .el-tabs--left .el-tabs__nav-wrap.is-left::after {
    height: 0;
  }

  /deep/ .el-tabs--left .el-tabs__header.is-left {
    margin-right: 60px;
  }

  /deep/ .el-tabs__nav .is-left {
    text-align: center;
    font-size: 16px;
    height: 55px;
  }

  /deep/ .el-tabs--card > .el-tabs__header .el-tabs__nav {
    border-bottom: 1px solid #E4E7ED;
    border-top: none;
    border-left: none;
    border-right: none;
    border-radius: 4px 4px 0 0;
    box-sizing: border-box;
  }

  /deep/ .el-form-item__label {
    text-align: left;
  }

  /*收藏列表*/
  .project-content {
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .course-tag {
    padding: 1px 5px;
    margin: 0 10px 0 0;
  }

  .project-item {
    width: 100%;
    height: 100px;
    background: #fff;
    margin-bottom: 20px;
    display: flex;
    flex-direction: row;
    cursor: pointer;
  }

  .project-item:hover {
    background-color: #f4f5f5;
  }

  .item-thumb img {
    width: 165px;
    height: 100px;
    border-radius: 4px;
    text-align: center;
    overflow: hidden;
    margin-right: 30px;
  }

  .item-info {
    width: 776px;
    height: 100px;
    display: flex;
    flex-direction: column;
    position: relative;
  }

  .item-top {
    width: 100%;
    height: 14px;
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-top: 20px;
  }

  .item-name {
    height: 14px;
    font-size: 14px;
    font-weight: 600;
    color: #333;
    line-height: 14px;
  }

  .order-num {
    height: 12px;
    font-size: 12px;
    font-weight: 400;
    color: #666;
    line-height: 12px;
    margin-right: 30px;
    margin-left: auto;
  }

  .item-time {
    height: 12px;
    font-size: 12px;
    font-weight: 400;
    color: #666;
    line-height: 12px;
  }

  .item-bottom {
    width: 100%;
    height: 14px;
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-top: 30px;
  }

  .item-price {
    height: 14px;
    font-size: 14px;
    font-weight: 400;
    color: #666;
    line-height: 14px;
  }

  .item-free {
    height: 14px;
    font-size: 14px;
    font-weight: 400;
    color: #04c877;
    line-height: 14px;
  }

  .item-status {
    height: 14px;
    font-size: 14px;
    font-weight: 400;
    color: #666;
    line-height: 14px;
    margin-left: auto;
  }


  .act {
    color: #ff5068;
  }

  .suc {
    color: #00df82;
  }
</style>
